const jwt = require('jsonwebtoken');
const { pool } = require('../config/database');

// JWT认证中间件
const authenticateToken = async (ctx, next) => {
  const authHeader = ctx.headers.authorization;
  const token = authHeader && authHeader.split(' ')[1];
  
  if (!token) {
    ctx.status = 401;
    ctx.body = { success: false, error: '访问令牌缺失' };
    return;
  }
  
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your_super_secret_jwt_key_here_music_app_2024');
    
    // 验证用户是否存在
    const [users] = await pool.execute(
      'SELECT id, username, email, avatar FROM users WHERE id = ?',
      [decoded.id]
    );
    
    if (users.length === 0) {
      ctx.status = 403;
      ctx.body = { success: false, error: '用户不存在' };
      return;
    }
    
    ctx.user = users[0];
    await next();
  } catch (error) {
    ctx.status = 403;
    ctx.body = { success: false, error: '令牌无效或已过期' };
  }
};

// 生成JWT令牌
const generateToken = (user) => {
  return jwt.sign(
    { id: user.id, username: user.username },
    process.env.JWT_SECRET || 'your_super_secret_jwt_key_here_music_app_2024',
    { expiresIn: '7d' }
  );
};

module.exports = {
  authenticateToken,
  generateToken
};